package cn.sibu.plugin.authorize.util;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ListAdapter;
import android.widget.ListView;



import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class CommonUtil {

	public static void showInfoDialog(Context context, String message) {
		showInfoDialog(context, message, "提示", "确定", null);
	}

	public static void showInfoDialog(Context context, String message,
			String titleStr , String positiveStr,
			DialogInterface.OnClickListener onClickListener) {
		AlertDialog.Builder localBuilder = new AlertDialog.Builder(context);
		localBuilder.setTitle(titleStr);
		 localBuilder.setMessage(message);
		if (onClickListener == null)
			onClickListener = new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {

				}
			};
		localBuilder.setPositiveButton(positiveStr, onClickListener);
		localBuilder.show();
	}

	public static String md5(String paramString) {
		String returnStr;
		try {
			MessageDigest localMessageDigest = MessageDigest.getInstance("MD5");
			localMessageDigest.update(paramString.getBytes());
			returnStr = byteToHexString(localMessageDigest.digest());
			return returnStr;
		} catch (Exception e) {
			return paramString;
		}
	}

	/**
	 * 将指定byte数组转换成16进制字符串
	 * 
	 * @param b
	 * @return
	 */
	public static String byteToHexString(byte[] b) {
		StringBuffer hexString = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			String hex = Integer.toHexString(b[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			hexString.append(hex.toUpperCase());
		}
		return hexString.toString();
	}

	/**
	 * 判断当前是否有可用的网络以及网络类型 0：无网络 1：WIFI 2：CMWAP 3：CMNET
	 * 
	 * @param context
	 * @return
	 */
	public static int isNetworkAvailable(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			return 0;
		} else {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						NetworkInfo netWorkInfo = info[i];
						if (netWorkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
							return 1;
						} else if (netWorkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
							String extraInfo = netWorkInfo.getExtraInfo();
							if ("cmwap".equalsIgnoreCase(extraInfo)
									|| "cmwap:gsm".equalsIgnoreCase(extraInfo)) {
								return 2;
							}
							return 3;
						}
					}
				}
			}
		}
		return 0;
	}

	/**
	 * 获取现在时间
	 * 
	 * @return 返回短时间字符串格式yyyy-MM-dd HH:mm:ss
	 */

	public static String getStringDate() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = formatter.format(currentTime);
		return dateString;
	}

	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	public static int getScreenPicHeight(int screenWidth, Bitmap bitmap) {
		int picWidth = bitmap.getWidth();
		int picHeight = bitmap.getHeight();
		int picScreenHeight = 0;
		picScreenHeight = (screenWidth * picHeight) / picWidth;
		return picScreenHeight;
	}


	private static Drawable createDrawable(Drawable d, Paint p) {

		BitmapDrawable bd = (BitmapDrawable) d;
		Bitmap b = bd.getBitmap();
		Bitmap bitmap = Bitmap.createBitmap(bd.getIntrinsicWidth(),
				bd.getIntrinsicHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		canvas.drawBitmap(b, 0, 0, p); // 关键代码，使用新的Paint画原图，

		return new BitmapDrawable(bitmap);
	}

	/** 设置Selector。 本次只增加点击变暗的效果，注释的代码为更多的效果 */
	public static StateListDrawable createSLD(Context context, Drawable drawable) {
		StateListDrawable bg = new StateListDrawable();
		int brightness = 50 - 127;
		ColorMatrix cMatrix = new ColorMatrix();
		cMatrix.set(new float[] { 1, 0, 0, 0, brightness, 0, 1, 0, 0,
				brightness,// 改变亮度
				0, 0, 1, 0, brightness, 0, 0, 0, 1, 0 });

		Paint paint = new Paint();
		paint.setColorFilter(new ColorMatrixColorFilter(cMatrix));

		Drawable normal = drawable;
		Drawable pressed = createDrawable(drawable, paint);
		bg.addState(new int[] { android.R.attr.state_pressed, }, pressed);
		bg.addState(new int[] { android.R.attr.state_focused, }, pressed);
		bg.addState(new int[] { android.R.attr.state_selected }, pressed);
		bg.addState(new int[] {}, normal);
		return bg;
	}

	public static Bitmap getImageFromAssetsFile(Context ct, String fileName) {
		Bitmap image = null;
		AssetManager am = ct.getAssets();
		try {
			InputStream is = am.open(fileName);
			image = BitmapFactory.decodeStream(is);
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return image;

	}

	// public static <Params, Progress, Result> void executeAsyncTask(
	// AsyncTask<Params, Progress, Result> task, Params... params) {
	// if (Build.VERSION.SDK_INT >= 11) {
	// task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
	// } else {
	// task.execute(params);
	// }
	// }

	public static String getUploadtime(long created) {
		StringBuffer when = new StringBuffer();
		int difference_seconds;
		int difference_minutes;
		int difference_hours;
		int difference_days;
		int difference_months;
		long curTime = System.currentTimeMillis();
		difference_months = (int) (((curTime / 2592000) % 12) - ((created / 2592000) % 12));
		if (difference_months > 0) {
			when.append(difference_months + "月");
		}

		difference_days = (int) (((curTime / 86400) % 30) - ((created / 86400) % 30));
		if (difference_days > 0) {
			when.append(difference_days + "天");
		}

		difference_hours = (int) (((curTime / 3600) % 24) - ((created / 3600) % 24));
		if (difference_hours > 0) {
			when.append(difference_hours + "小时");
		}

		difference_minutes = (int) (((curTime / 60) % 60) - ((created / 60) % 60));
		if (difference_minutes > 0) {
			when.append(difference_minutes + "分钟");
		}

		difference_seconds = (int) ((curTime % 60) - (created % 60));
		if (difference_seconds > 0) {
			when.append(difference_seconds + "秒");
		}

		return when.append("前").toString();
	}

	// public static boolean hasToken(Context ct) {
	// String token = SharePrefUtil.getString(ct, "token", "");
	// if (TextUtils.isEmpty(token)) {
	// return false;
	// } else {
	// return true;
	// }
	// }

	public static void setListViewHeightBasedOnChildren(ListView listView) {
		// 获取ListView对应的Adapter
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}
		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) { // listAdapter.getCount()返回数据项的数目
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0); // 计算子项View 的宽高
			totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
		}
		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		// listView.getDividerHeight()获取子项间分隔符占用的高度
		// params.height最后得到整个ListView完整显示需要的高度
		listView.setLayoutParams(params);
	}

	public static String formatDate() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		return sdf.format(new Date());
	}

	/**
	 * 
	 * @Title: regexMate
	 * @Description: TODO(匹配正则)
	 * @param @param regex
	 * @param @param str
	 * @param @return 设定文件
	 * @return boolean 返回类型
	 * @throws
	 */
	public static boolean regexMate(String regex, String str) {
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(str);
		return matcher.matches();

	}

	/**
	 * 
	 * TODO<间隔时间 >
	 * 
	 * @param @param previousTime 上一个时间
	 * @param @param currentTime 当前时间
	 * @param @return
	 * @throw
	 * @return boolean
	 */
	public static long intervalTime(long previousTime, long currentTime) {
		long time = currentTime - previousTime;
		return time;
	}

	/**
	 * 
	 * TODO 记录连接服务接口成功的时间
	 * 
	 * @param @param context
	 * @param @param str
	 * @throw
	 * @return void
	 */
	// 思埠之家工具类
	public static void recordCurrentTime(Context context) {
//		long currentTime = System.currentTimeMillis();
//		SharedPreferencesUitls.saveLong(context,
//				ConfigKeyName.TOSERVERSUCCESSTIME, currentTime);
	}
	// 检查用户状态是否为已审
	public static boolean checkAccess(Context ct) {
		boolean flag = false;
//		if (TextUtils.isEmpty(SharedPreferencesUitls.getString(ct, ConfigKeyName.USERSTATUS, ""))) {
//			Intent intent = new Intent(ct, LoginActivity.class);
//			intent.putExtra(ResponseCode.TOKENVOID, ResponseCode.TOKENVOID);
//			ct.startActivity(intent);
//		} else {
//			int status = Integer.parseInt(SharedPreferencesUitls.getString(ct,
//					ConfigKeyName.USERSTATUS, ""));
//			if (RequestParamName.AUDITED_AGENCY == status) {
//				flag = true;
//			}
//		}
		return flag;
	}
	
	// 检查用户是否为总代
	public static boolean isAgent(Context ct) {
		boolean flag = false;
//		if (SharedPreferencesUitls.getString(ct, ConfigKeyName.GROUPID, "")
//				.equals("")) {
//			Intent intent = new Intent(ct, LoginActivity.class);
//			ct.startActivity(intent);
//		} else {
//			int group = Integer.parseInt(SharedPreferencesUitls.getString(ct,
//					ConfigKeyName.GROUPID, ""));
//			if (7 == group) {
//				flag = true;
//			}
//		}
		return flag;
	}

	public static boolean checkBlackList(String str){
		String[] strs={"广州思埠集团","广州思埠生物科技有限公司","广州思埠网络开发有限公司","思埠集团","思埠生物","黛莱美","天使之魅","美颜水",
				"欧蒂芙","紓雅","纾雅","素佳","BB霜","总代","总 代","总代理","总经销商","全国","全国总代"};
		for(int i=0;i<strs.length;i++){
			if(str.indexOf(strs[i])!=-1||str.equals(strs[i])){
				return true;
			}
		}
		return false;
	}
	//判断用户输入的字符是否为数字
	public static boolean isNumeric(String str){ 
		   Pattern pattern = Pattern.compile("[0-9]*"); 
		   Matcher isNum = pattern.matcher(str);
		   if( !isNum.matches() ){
		       return false; 
		   } 
		   return true; 
		}
	
	//检查旺旺号长度
	public static boolean checkWangwang(String wangwang){
		int len = 0;
		for (int i = 0; i < wangwang.length(); i++) {
	               int length = wangwang.codePointAt(i);
	               if(length>=0&&length<=128){
	                    len += 1;
	                }else{
	                    len += 2;
	                }
                }
		if(len>=5&&len<=25){
			return true;
		}
		return false;
	}
//	connection.addRequestProperty("User-Agent","sibu/1.2(huawei;android 19;800*800)");
	
	public static String getUserAgentDate(Context context){
		String agent = null;
		String versionName = null ;
		PackageManager manager = context.getPackageManager();
		String agentVersion = "1.1.1";  // 授权的版本号
		
		try {
			// getPackageName() 返回当前应用程序的包名
			PackageInfo packageInfo = manager.getPackageInfo(context.getPackageName(),
					0);
			versionName = packageInfo.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		String device = android.os.Build.MODEL;
 		String version = android.os.Build.VERSION.RELEASE;
 		
 		WindowManager manage=((Activity) context).getWindowManager();
        Display display=manage.getDefaultDisplay();
        int height=display.getHeight();
        int width=display.getWidth();
 		
		agent = "sibu/"+versionName+"/"+agentVersion+"("+device+";"+version+";"+width+"*"+height+")";
		return agent ;
	}
	public  static void checkTokenByServerCodeAndUpdateInfo(String code){
		if(ResponseCode.TOKENVOID.equals(code)){ //token过期
			//跳转到登录界面

		}

	}


	
	protected static final int MSG_UPDATE = 10;
	protected static final int MSG_NULL = 11;
	protected static final int UPDATE_TIME = 3000;
	
	
	
	public static boolean takeIs(Context context,Handler handler){
//		long previousTime = SharedPreferencesUitls.getLong(context,
//				ConfigKeyName.TOSERVERSUCCESSTIME, 0);
//		if (previousTime == 0) {
//			return false;
//		}
//		// 当前时间
//		long currentTime = System.currentTimeMillis();
//		long invalTime = CommonUtil.intervalTime(previousTime, currentTime);
//		int day = (int) (invalTime / (1000 * 60 * 60 * 24));
//		// 超过七天
//		if (day > 7) {
//			Log.e("TAG", "----false---02");
//			return false;
//		} else {
//			// 如果用户token失效，进行登录
//			String token = SharedPreferencesUitls.getString(context,
//					ConfigKeyName.TOKEN, null);
//			String uid = SharedPreferencesUitls.getString(context,
//					ConfigKeyName.UID, null);
//			if (TextUtils.isEmpty(token) == false
//					&& TextUtils.isEmpty(uid) == false) {
//				newInfo(context, token, uid,handler);
//				return true;
//			} else {
//				 return false;
//			}
//
//		}
		return false;
	}
	
	 /**
	  * 
	  * TODO  判断用户token是否过期的判断方法
	  * @param @param context
	  * @param @return
	  * @throw 
	  * @return boolean
	  */
	
	 
	
	public static boolean tokeIsEffective(  Context context) {

//		// 连接服务器后更新的时间
//		long previousTime = SharedPreferencesUitls.getLong(context,
//				ConfigKeyName.TOSERVERSUCCESSTIME, 0);
//		if (previousTime == 0) {
//
//			return false;
//		}
//		// 当前时间
//		long currentTime = System.currentTimeMillis();
//		long invalTime = CommonUtil.intervalTime(previousTime, currentTime);
//		int day = (int) (invalTime / (1000 * 60 * 60 * 24));
//		// 超过七天
//		if (day > 7) {
//			 return false;
//		} else {
//			// 如果用户token失效，进行登录
//			String token = SharedPreferencesUitls.getString(context,
//					ConfigKeyName.TOKEN, null);
//			String uid = SharedPreferencesUitls.getString(context,
//					ConfigKeyName.UID, null);
//			if (TextUtils.isEmpty(token) == false
//					&& TextUtils.isEmpty(uid) == false) {
//				// 请求最新用户信息接口
//
////			    return newInfo(context, token, uid);
//				return true;
//
//			} else {
//				Log.e("TAG", "----false---02");
//				return false;
//			}
//
//		}
		return false;
	}
	
	  private static boolean aa = true ;
//	public static void newInfo(final Context context,final String token,final String uid,final Handler handler){
//		// 请求最新用户信息接口
//
//		HttpUtils httpUtils = new HttpUtils();
//		RequestParams params = new RequestParams();
//		httpUtils.configUserAgent(CommonUtil.getUserAgentDate(context));
//		params.addBodyParameter(RequestParamName.AT, SBApi.GETUSER);
//		params.addBodyParameter(RequestParamName.TOKEN,token);
//		params.addBodyParameter(RequestParamName.UID,uid);
//		httpUtils.send(HttpMethod.POST, SBApi.BASE_URL_AGENCY,params, new RequestCallBack<String>() {
//
//			@Override
//			public void onFailure(HttpException arg0, String arg1) {
//				  Toast.makeText(context, "联网失败",0).show();
//			}
//
//			@Override
//			public void onSuccess(ResponseInfo<String> arg0) {
//				 String reString = arg0.result;
//				 CommonUtil.recordCurrentTime(context);
//			     aa =  processUserDate(context,reString);
//
//			    L.e("TAG", "----aa02："+aa);
//			     Message message = new Message();
//			     message.obj = aa;
//			     message.what = 2212121;
//
//			     if(handler!=null)
//			     handler.sendMessage(message);
//			}
//		});
//
//
//	}
//
//
//
//
//	protected static boolean  processUserDate(Context context, String result) {
//		ResponseFilter mFilter = GsonUtils.json2Bean(result,
//				ResponseFilter.class);
//		//System.out.println("token状态码："+mFilter.code);
//		if (mFilter.code.equals(ResponseCode.TOKENVOID)) {
//			  return false;
//			}else{
//				 return true;
//			}
//
//
//
//	}
//
//	/**
//	 * TODO 返回登录名
//	 * @param @param context
//	 * @param @return
//	 * @throw
//	 * @return String
//	 */
//	public static String username(Context context){
//
//		String username = SharedPreferencesUitls.getString(context,
//				ConfigKeyName.PHOTOUSERNAME, "");
//		return username;
//
//	}
//
  
}
